/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean.TX.CustomerIOTRPortal;

import Helper.Helper_LineItem;
import session.TX.*;
import entity.*;
import Web_Helper.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Randall Chia
 */
@ManagedBean(name = "cartBean")
@SessionScoped
public class ShoppingCartMB {

    @EJB
    private TransactionManagerSBRemote transactionManager;
    
    @EJB
    private ULPSBRemote loyaltypointsManager;
    
    @EJB
    private UsersSBRemote userManager;
    
    //@EJB
    //private ShoppingCartSBRemote cartManager;
    
    @ManagedProperty(value = "#{fakeMainPortalMB}")
    private FakeMainPortalMB portalManagedBean;

    private List<Helper_LineItem> cart;
    private List<Helper_LineItem> addStuff = new ArrayList<Helper_LineItem>();
    private String purchaseStatusMSG = "DEFAULT";

    /** Creates a new instance of ShoppingCartMB */
    public ShoppingCartMB() {
        addStuff.add(new Helper_LineItem(632, "Big and Tasty Meal", 1, 6.50, "Mc'Donalds", 2, "Clementi"));  
        addStuff.add(new Helper_LineItem(633, "Zinger Burger", 1, 3.50, "KFC", 3, "VivoCity"));
        //addStuff.add(new Helper_LineItem(634, "Whopper", 1, 4.00, "Burger King", 4, "Plaza Singapura"));
        //addStuff.add(new Helper_LineItem(635, "Whopper", 1, 4.00, "Burger King", 1, "Clementi"));
        
        
    }
    
    
    
    
    
    
    public void printCart(){
        System.out.println(">>> cartBean printing the shopping cart of user: " + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("Semail").toString());
        for(Helper_LineItem  o : getCartManager().getCart()){
            System.out.println("*************** " + o);
        }
    }
    
    
    
    
    
    
    public void updateListenAction(RowEditEvent event){
        getCartManager().setCart(cart);
    }
    

    //Retrieve the cart items
    public List<Helper_LineItem> getItems() {
        if (cart == null) {
            cart = getCartManager().getCart();
        }
        return cart;
    }//------------------------------------------------------------------------------------------

    //Delete an item from the cart
    public void removeFromCart(Helper_LineItem item) {
        cart.remove(item);
        getCartManager().setCart(cart);
        //getCartManager().cart_remove(item);
    }//------------------------------------------------------------------------------------------

    //Add one or more Line Items into the cart
    public void addItems() {
        cart = null;
        getCartManager().cart_addMultipleItems(addStuff);
    }//------------------------------------------------------------------------------------------

    //clear the cart items
    public void emptyCart() {
        cart = null;
        getCartManager().cart_removeAllItems();
    }//------------------------------------------------------------------------------------------

    //get the subtotal.
    public double getSubtotal() {
        return getCartManager().getSubtotal();
    }//------------------------------------------------------------------------------------------

    //Perform validation of a payment
    public void validatePayment() {

        boolean validationResult = false;
        try {
            validationResult = Helper_PaymentValidator.validatePayment();
        } catch (IOException e) {
        }

        if (validationResult == true) {
            System.out.println("Payment Validation: SUCCESS");


            this.doTransactionLog();
            this.emptyCart();
            purchaseStatusMSG = "SUCCESS";
            
        }//end THEN block
        else {
            System.out.println("Payment Validation: FAIL");
            purchaseStatusMSG = "FAIL";
        }

    }//------------------------------------------------------------------------------------------

    public void doTransactionLog() {
        
        if(cart.isEmpty()) return; //Don't do anything if cart is empty.
        
        String customerEmail = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("Semail").toString();
        Long customerID = Long.valueOf(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sid").toString());
        
        
        //Find the customer
        List<Users> userList = userManager.getAllUser();
        
        Integer customer_age = 0;
        String customer_country = " ";
        
        for(Users o: userList){
            if(o.getId().equals(customerID)){

                Calendar cal1 = Calendar.getInstance();
                int thisYear = cal1.get(Calendar.YEAR);
                
                Calendar cal2 = Calendar.getInstance();
                cal2.setTime(o.getBirthDate());
                int customerBirthYear = cal2.get(Calendar.YEAR);
                
                customer_age = thisYear - customerBirthYear;                      
                customer_country = o.getCountry().getCountry();
            }
        }

        System.out.println("Customer " + customerEmail + " checked out their shopping cart");

        Calendar transaction_timestamp = Calendar.getInstance();
        
        double subtotal = this.getSubtotal();
        Integer loyaltyPointsAwarded = loyaltypointsManager.calculateLoyaltyPoints(transaction_timestamp.getTime(), customerEmail, subtotal);

        //populate the database with PurchasedItems
        List<PurchasedItem> purchasedItemList = new ArrayList<PurchasedItem>();

        for (Helper_LineItem item : cart) {
            PurchasedItem itemEntity = transactionManager.createPurchasedItem_Regular(
                    transaction_timestamp,
                    customerEmail,
                    item.getSeller(),
                    item.getItem_name(),
                    item.getItem_ID(),
                    item.getItem_quantity() * item.getItem_price(),
                    customer_country,
                    customer_age,
                    item.getItem_outletID());


            purchasedItemList.add(itemEntity);
        }//end for

        transactionManager.createTransactionEntry(
                transaction_timestamp,
                customerEmail,
                loyaltyPointsAwarded,
                subtotal,
                purchasedItemList);
    }//------------------------------------------------------------------------------------------

    


    /**
     * @return the cart
     */
    public List<Helper_LineItem> getCart() {
        return cart;
    }

    /**
     * @param cart the cart to set
     */
    public void setCart(List<Helper_LineItem> cart) {
        this.cart = cart;
    }

    /**
     * @return the addStuff
     */
    public List<Helper_LineItem> getAddStuff() {
        return addStuff;
    }

    /**
     * @param addStuff the addStuff to set
     */
    public void setAddStuff(List<Helper_LineItem> addStuff) {
        this.addStuff = addStuff;
    }

    /**
     * @return the portalManagedBean
     */
    public FakeMainPortalMB getPortalManagedBean() {
        return portalManagedBean;
    }

    /**
     * @param portalManagedBean the portalManagedBean to set
     */
    public void setPortalManagedBean(FakeMainPortalMB portalManagedBean) {
        this.portalManagedBean = portalManagedBean;
    }

    //Retrieve the cartManager, which is the session bean instance injected in the FakeMainPortalMB
    public ShoppingCartSBRemote getCartManager() {
        return portalManagedBean.getCartManager();
    }

    /**
     * @return the purchaseStatusMSG
     */
    public String getPurchaseStatusMSG() {
        return purchaseStatusMSG;
    }

    /**
     * @param purchaseStatusMSG the purchaseStatusMSG to set
     */
    public void setPurchaseStatusMSG(String purchaseStatusMSG) {
        this.purchaseStatusMSG = purchaseStatusMSG;
    }

    
    
    
    
    
    
    
    
    
    
}
